import os
from django.shortcuts import render
from django.http import HttpResponseRedirect
from loguru import logger
from rest_framework import status
from rest_framework.request import Request
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters

from apps.Order.filters import OrderFilter
from apps.Order.serializers import ReadOrderSerializer, WriteOrderSerializer
from op_drf.pagination import Pagination
from op_drf.response import SuccessResponse, ErrorResponse
from op_drf.dj_utils import set_delete, create_by_serializer
from op_drf.viewsets import CustomModelViewSet

from apps.Order.models import Order


# Create your views here.

class OrderView(CustomModelViewSet):
    """
    处方信息的CRUD
    """
    queryset = Order.objects.filter(is_delete=False)
    serializer_class = ReadOrderSerializer  # 序列化器
    create_serializer_class = WriteOrderSerializer
    update_serializer_class = WriteOrderSerializer
    # 分页
    pagination_class = Pagination
    # 筛选
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = OrderFilter
    search_fields = ("id", )
    filter_fields = ("id", )
    ordering_fields = ("-id",)
    ordering = ["-create_datetime"]

    # def create(self, request: Request, *args, **kwargs):
    #     logger.debug("前端传入的数据： %s" % request.data)
    #     logger.debug("请求携带的数据： %s" % kwargs)
    #     logger.debug(request.data)
    #     serializer = self.get_serializer(data=request.data)
    #
    #     logger.debug(1)
    #     serializer.is_valid(raise_exception=True)
    #     logger.debug(1)
    #     self.perform_create(serializer)
    #     logger.debug(1)
    #     logger.debug(serializer.data)
    #     logger.debug(1)
    #     headers = self.get_success_headers(serializer.data)
    #     logger.debug("序列化后的数据： %s" % serializer.data)
    #     return SuccessResponse(serializer.data, headers=headers)

    def update(self, request: Request, *args, **kwargs):
        logger.debug("前端传入的数据： %s" % request.data)
        logger.debug("请求携带的数据： %s" % kwargs)
        instance = self.get_object()
        msg = ""
        if not instance:
            msg = "请确定要修改的药方"
            return ErrorResponse(msg=msg)

        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        if getattr(instance, "_prefetched_objects_cache", None):
            instance._prefetched_objects_cache = {}
        if hasattr(self, "handle_logging"):
            self.handle_logging(request, instance=instance, *args, **kwargs)
        logger.debug("序列化后的数据： %s" % serializer.data)
        return SuccessResponse(serializer.data)
